'use client'

import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Loader2, Play, CheckCircle, XCircle, Send, Plus, Minus } from 'lucide-react'
import { toast } from 'sonner'

// SOAP 송신 함수들 import
import { confirmTestPCR, confirmPCR } from '@/lib/soap/ecc/send/pcr-confirm'
import { cancelTestRFQ, cancelRFQ } from '@/lib/soap/ecc/send/cancel-rfq'
import { sendTestRFQInformation, sendRFQInformation } from '@/lib/soap/ecc/send/rfq-info'
import { createTestPurchaseOrder, createPurchaseOrder } from '@/lib/soap/ecc/send/create-po'

interface TestResult {
  success: boolean
  message: string
  responseData?: string
  timestamp: string
  duration?: number
  statusCode?: number
  endpoint?: string
  headers?: Record<string, string>
  requestXml?: string
  requestHeaders?: Record<string, string>
}

export default function ECCSenderTestPage() {
  const [isLoading, setIsLoading] = useState<{ [key: string]: boolean }>({})
  const [testResults, setTestResults] = useState<{ [key: string]: TestResult }>({})

  // 테스트 실행 공통 함수
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const runTest = async (testName: string, testFunction: () => Promise<any>) => {
    setIsLoading(prev => ({ ...prev, [testName]: true }))
    const startTime = Date.now()
    
    try {
      const result = await testFunction()
      const duration = Date.now() - startTime
      
      const testResult: TestResult = {
        success: result.success,
        message: result.message,
        responseData: result.responseData,
        timestamp: new Date().toLocaleString('ko-KR'),
        duration,
        statusCode: result.statusCode,
        endpoint: result.endpoint,
        headers: result.headers,
        requestXml: result.requestXml,
        requestHeaders: result.requestHeaders
      }
      
      setTestResults(prev => ({ ...prev, [testName]: testResult }))
      
      if (result.success) {
        toast.success(`${testName} 테스트 성공`)
      } else {
        toast.error(`${testName} 테스트 실패: ${result.message}`)
      }
    } catch (error) {
      const testResult: TestResult = {
        success: false,
        message: error instanceof Error ? error.message : '알 수 없는 오류',
        timestamp: new Date().toLocaleString('ko-KR'),
        duration: Date.now() - startTime
      }
      
      setTestResults(prev => ({ ...prev, [testName]: testResult }))
      toast.error(`${testName} 테스트 오류: ${testResult.message}`)
    } finally {
      setIsLoading(prev => ({ ...prev, [testName]: false }))
    }
  }

  // PCR 확인 테스트
  const [pcrData, setPcrData] = useState({
    PCR_REQ: 'TEST_PCR01',
    PCR_REQ_SEQ: '00001',
    PCR_DEC_DATE: '20241201',
    EBELN: 'TEST_PO01',
    EBELP: '00010',
    PCR_STATUS: 'A',
    WAERS: 'KRW',
    PCR_NETPR: '1000.00',
    PEINH: '1',
    PCR_NETWR: '1000.00',
    CONFIRM_CD: 'CONF',
    CONFIRM_RSN: '테스트 확인'
  })

  // RFQ 취소 테스트
  const [rfqCancelData, setRfqCancelData] = useState({
    ANFNR: 'TEST_RFQ_001'
  })

  // RFQ 정보 전송 테스트
  const [rfqInfoData, setRfqInfoData] = useState({
    // 헤더 정보
    ANFNR: 'RFQ0000001',
    LIFNR: '1000000001',
    WAERS: 'KRW',
    ZTERM: '0001',
    INCO1: 'FOB',
    INCO2: 'Seoul, Korea',
    MWSKZ: 'V0',
    LANDS: 'KR',
    VSTEL: '001',
    LSTEL: '001',
    // 아이템 정보
    ANFPS: '00001',
    NETPR: '1000.00',
    NETWR: '1000.00',
    BRTWR: '1100.00',
    LFDAT: '20241201'
  })

  // PO 생성 테스트
  const [poData, setPoData] = useState({
    header: {
      ANFNR: 'TEST001',
      LIFNR: '1000000001',
      ZPROC_IND: 'A',
      ANGNR: 'TEST001',
      WAERS: 'KRW',
      ZTERM: '0001',
      INCO1: 'FOB',
      INCO2: 'Seoul, Korea',
      MWSKZ: 'V0',
      LANDS: 'KR',
      ZRCV_DT: '20241201',
      ZATTEN_IND: 'Y',
      IHRAN: '20241201',
      TEXT: 'Test PO Creation',
      LSTEL: '',
      VSTEL: '',
      ZDLV_CNTLR: '',
      ZDLV_PRICE_NOTE: '',
      ZDLV_PRICE_T: ''
    },
    items: [{
      ANFNR: 'TEST001',
      ANFPS: '00001',
      LIFNR: '1000000001',
      NETPR: '1000.00',
      PEINH: '1',
      BPRME: 'EA',
      NETWR: '1000.00',
      BRTWR: '1100.00',
      LFDAT: '20241201',
      EBELP: '',
      ZCON_NO_PO: ''
    }],
    prReturn: [{
      ANFNR: 'TEST001',
      ANFPS: '00001',
      EBELN: 'PR001',
      EBELP: '00001',
      MSGTY: 'S',
      MSGTXT: 'Test message'
    }]
  })

  // PO 아이템 관리 함수들
  const addPoItem = () => {
    const newItemIndex = poData.items.length + 1
    setPoData(prev => ({
      ...prev,
      items: [...prev.items, {
        ANFNR: prev.header.ANFNR,
        ANFPS: String(newItemIndex).padStart(5, '0'),
        LIFNR: prev.header.LIFNR,
        NETPR: '0.00',
        PEINH: '1',
        BPRME: 'EA',
        NETWR: '0.00',
        BRTWR: '0.00',
        LFDAT: prev.header.IHRAN,
        EBELP: '',
        ZCON_NO_PO: ''
      }]
    }))
  }

  const removePoItem = (index: number) => {
    if (poData.items.length > 1) {
      setPoData(prev => ({
        ...prev,
        items: prev.items.filter((_, i) => i !== index)
      }))
    }
  }

  const updatePoItem = (index: number, field: string, value: string) => {
    setPoData(prev => ({
      ...prev,
      items: prev.items.map((item, i) =>
        i === index ? { ...item, [field]: value } : item
      )
    }))
  }

  const updatePoHeader = (field: string, value: string) => {
    setPoData(prev => ({
      ...prev,
      header: { ...prev.header, [field]: value }
    }))
  }

  return (
    <div className="container mx-auto py-8 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">ECC SOAP Sender 테스트</h1>
          <p className="text-muted-foreground mt-2">
            4개의 ECC SOAP 송신 라이브러리를 테스트합니다
          </p>
        </div>
        <Badge variant="outline" className="text-sm">
          개발/테스트 환경
        </Badge>
      </div>

      <Tabs defaultValue="pcr-confirm" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="pcr-confirm">PCR 확인</TabsTrigger>
          <TabsTrigger value="rfq-cancel">RFQ 취소</TabsTrigger>
          <TabsTrigger value="rfq-info">RFQ 정보</TabsTrigger>
          <TabsTrigger value="po-create">PO 생성</TabsTrigger>
        </TabsList>

        {/* PCR 확인 탭 */}
        <TabsContent value="pcr-confirm" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Send className="h-5 w-5" />
                PCR (Price Change Request) 확인
              </CardTitle>
              <CardDescription>
                PCR 확인 요청을 ECC로 전송합니다. (IF_ECC_EVCP_PCR_CONFIRM)
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="pcr-req">PCR 요청번호 (필수)</Label>
                  <Input
                    id="pcr-req"
                    value={pcrData.PCR_REQ}
                    onChange={(e) => setPcrData(prev => ({ ...prev, PCR_REQ: e.target.value }))}
                    placeholder="PCR 요청번호 (최대 10자)"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="pcr-seq">PCR 요청순번 (필수)</Label>
                  <Input
                    id="pcr-seq"
                    value={pcrData.PCR_REQ_SEQ}
                    onChange={(e) => setPcrData(prev => ({ ...prev, PCR_REQ_SEQ: e.target.value }))}
                    placeholder="PCR 요청순번 (5자리 숫자)"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="pcr-date">PCR 결정일 (필수)</Label>
                  <Input
                    id="pcr-date"
                    value={pcrData.PCR_DEC_DATE}
                    onChange={(e) => setPcrData(prev => ({ ...prev, PCR_DEC_DATE: e.target.value }))}
                    placeholder="YYYYMMDD 형식"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ebeln">구매오더 (필수)</Label>
                  <Input
                    id="ebeln"
                    value={pcrData.EBELN}
                    onChange={(e) => setPcrData(prev => ({ ...prev, EBELN: e.target.value }))}
                    placeholder="구매오더 번호"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ebelp">구매오더 품번 (필수)</Label>
                  <Input
                    id="ebelp"
                    value={pcrData.EBELP}
                    onChange={(e) => setPcrData(prev => ({ ...prev, EBELP: e.target.value }))}
                    placeholder="구매오더 품번"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="pcr-status">PCR 상태 (필수)</Label>
                  <Input
                    id="pcr-status"
                    value={pcrData.PCR_STATUS}
                    onChange={(e) => setPcrData(prev => ({ ...prev, PCR_STATUS: e.target.value }))}
                    placeholder="PCR 상태 (1자)"
                  />
                </div>
              </div>

              <Separator />

              <div className="flex gap-4">
                <Button
                  onClick={() => runTest('PCR 확인 (샘플)', () => confirmTestPCR())}
                  disabled={isLoading['PCR 확인 (샘플)']}
                  variant="outline"
                >
                  {isLoading['PCR 확인 (샘플)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Play className="mr-2 h-4 w-4" />
                  샘플 데이터로 테스트
                </Button>
                <Button
                  onClick={() => runTest('PCR 확인 (사용자)', () => confirmPCR(pcrData))}
                  disabled={isLoading['PCR 확인 (사용자)']}
                >
                  {isLoading['PCR 확인 (사용자)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Send className="mr-2 h-4 w-4" />
                  사용자 데이터로 전송
                </Button>
              </div>

              {/* 테스트 결과 표시 */}
              {(testResults['PCR 확인 (샘플)'] || testResults['PCR 확인 (사용자)']) && (
                <div className="space-y-2">
                  <h4 className="font-semibold">테스트 결과</h4>
                  {testResults['PCR 확인 (샘플)'] && (
                    <TestResultCard result={testResults['PCR 확인 (샘플)']} title="샘플 테스트" />
                  )}
                  {testResults['PCR 확인 (사용자)'] && (
                    <TestResultCard result={testResults['PCR 확인 (사용자)']} title="사용자 테스트" />
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* RFQ 취소 탭 */}
        <TabsContent value="rfq-cancel" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Send className="h-5 w-5" />
                RFQ (Request for Quotation) 취소
              </CardTitle>
              <CardDescription>
                RFQ 취소 요청을 ECC로 전송합니다. (IF_ECC_EVCP_CANCEL_RFQ)
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="anfnr-cancel">RFQ 번호 (필수)</Label>
                <Input
                  id="anfnr-cancel"
                  value={rfqCancelData.ANFNR}
                  onChange={(e) => setRfqCancelData(prev => ({ ...prev, ANFNR: e.target.value }))}
                  placeholder="RFQ 번호 (최대 10자)"
                />
              </div>

              <Separator />

              <div className="flex gap-4">
                <Button
                  onClick={() => runTest('RFQ 취소 (샘플)', () => cancelTestRFQ())}
                  disabled={isLoading['RFQ 취소 (샘플)']}
                  variant="outline"
                >
                  {isLoading['RFQ 취소 (샘플)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Play className="mr-2 h-4 w-4" />
                  샘플 데이터로 테스트
                </Button>
                <Button
                  onClick={() => runTest('RFQ 취소 (사용자)', () => cancelRFQ(rfqCancelData.ANFNR))}
                  disabled={isLoading['RFQ 취소 (사용자)']}
                  variant="destructive"
                >
                  {isLoading['RFQ 취소 (사용자)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Send className="mr-2 h-4 w-4" />
                  사용자 데이터로 취소
                </Button>
              </div>

              {/* 테스트 결과 표시 */}
              {(testResults['RFQ 취소 (샘플)'] || testResults['RFQ 취소 (사용자)']) && (
                <div className="space-y-2">
                  <h4 className="font-semibold">테스트 결과</h4>
                  {testResults['RFQ 취소 (샘플)'] && (
                    <TestResultCard result={testResults['RFQ 취소 (샘플)']} title="샘플 테스트" />
                  )}
                  {testResults['RFQ 취소 (사용자)'] && (
                    <TestResultCard result={testResults['RFQ 취소 (사용자)']} title="사용자 테스트" />
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* RFQ 정보 탭 */}
        <TabsContent value="rfq-info" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Send className="h-5 w-5" />
                RFQ 정보 전송
              </CardTitle>
              <CardDescription>
                RFQ 정보를 ECC로 전송합니다. (IF_EVCP_ECC_RFQ_INFORMATION)
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-4">
                <h4 className="font-semibold">RFQ 헤더 정보</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="rfq-anfnr">RFQ 번호 (필수)</Label>
                    <Input
                      id="rfq-anfnr"
                      value={rfqInfoData.ANFNR}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, ANFNR: e.target.value }))}
                      placeholder="RFQ 번호"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-lifnr">공급업체 계정 (필수)</Label>
                    <Input
                      id="rfq-lifnr"
                      value={rfqInfoData.LIFNR}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, LIFNR: e.target.value }))}
                      placeholder="공급업체 계정번호"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-waers">통화 (필수)</Label>
                    <Input
                      id="rfq-waers"
                      value={rfqInfoData.WAERS}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, WAERS: e.target.value }))}
                      placeholder="통화 코드 (예: KRW)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-zterm">지불조건 (필수)</Label>
                    <Input
                      id="rfq-zterm"
                      value={rfqInfoData.ZTERM}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, ZTERM: e.target.value }))}
                      placeholder="지불조건 키"
                    />
                  </div>
                </div>

                <h4 className="font-semibold">RFQ 아이템 정보</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="rfq-anfps">아이템 번호 (필수)</Label>
                    <Input
                      id="rfq-anfps"
                      value={rfqInfoData.ANFPS}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, ANFPS: e.target.value }))}
                      placeholder="RFQ 아이템 번호"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-netpr">순가격 (필수)</Label>
                    <Input
                      id="rfq-netpr"
                      value={rfqInfoData.NETPR}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, NETPR: e.target.value }))}
                      placeholder="순가격"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-netwr">순주문가격 (필수)</Label>
                    <Input
                      id="rfq-netwr"
                      value={rfqInfoData.NETWR}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, NETWR: e.target.value }))}
                      placeholder="순주문가격"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfq-brtwr">총주문가격 (필수)</Label>
                    <Input
                      id="rfq-brtwr"
                      value={rfqInfoData.BRTWR}
                      onChange={(e) => setRfqInfoData(prev => ({ ...prev, BRTWR: e.target.value }))}
                      placeholder="총주문가격"
                    />
                  </div>
                </div>
              </div>

              <Separator />

              <div className="flex gap-4">
                <Button
                  onClick={() => runTest('RFQ 정보 (샘플)', () => sendTestRFQInformation())}
                  disabled={isLoading['RFQ 정보 (샘플)']}
                  variant="outline"
                >
                  {isLoading['RFQ 정보 (샘플)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Play className="mr-2 h-4 w-4" />
                  샘플 데이터로 테스트
                </Button>
                <Button
                  onClick={() => runTest('RFQ 정보 (사용자)', async () => {
                    const rfqRequest = {
                      T_RFQ_HEADER: [{
                        ANFNR: rfqInfoData.ANFNR,
                        LIFNR: rfqInfoData.LIFNR,
                        WAERS: rfqInfoData.WAERS,
                        ZTERM: rfqInfoData.ZTERM,
                        INCO1: rfqInfoData.INCO1,
                        INCO2: rfqInfoData.INCO2,
                        MWSKZ: rfqInfoData.MWSKZ,
                        LANDS: rfqInfoData.LANDS,
                        VSTEL: rfqInfoData.VSTEL,
                        LSTEL: rfqInfoData.LSTEL
                      }],
                      T_RFQ_ITEM: [{
                        ANFNR: rfqInfoData.ANFNR,
                        ANFPS: rfqInfoData.ANFPS,
                        NETPR: rfqInfoData.NETPR,
                        NETWR: rfqInfoData.NETWR,
                        BRTWR: rfqInfoData.BRTWR,
                        LFDAT: rfqInfoData.LFDAT
                      }]
                    }
                    return sendRFQInformation(rfqRequest)
                  })}
                  disabled={isLoading['RFQ 정보 (사용자)']}
                >
                  {isLoading['RFQ 정보 (사용자)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Send className="mr-2 h-4 w-4" />
                  사용자 데이터로 전송
                </Button>
              </div>

              {/* 테스트 결과 표시 */}
              {(testResults['RFQ 정보 (샘플)'] || testResults['RFQ 정보 (사용자)']) && (
                <div className="space-y-2">
                  <h4 className="font-semibold">테스트 결과</h4>
                  {testResults['RFQ 정보 (샘플)'] && (
                    <TestResultCard result={testResults['RFQ 정보 (샘플)']} title="샘플 테스트" />
                  )}
                  {testResults['RFQ 정보 (사용자)'] && (
                    <TestResultCard result={testResults['RFQ 정보 (사용자)']} title="사용자 테스트" />
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* PO 생성 탭 */}
        <TabsContent value="po-create" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Send className="h-5 w-5" />
                PO (Purchase Order) 생성
              </CardTitle>
              <CardDescription>
                구매주문 생성 요청을 ECC로 전송합니다. (IF_ECC_EVCP_PO_CREATE) - 하나의 PO에 여러 PR 아이템들을 포함시키는 구조
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* PO 헤더 정보 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="font-semibold">PO 헤더 정보</h4>
                  <Badge variant="outline" className="text-xs">
                    {poData.items.length}개 아이템
                  </Badge>
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="po-anfnr">입찰번호 (ANFNR) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-anfnr"
                      value={poData.header.ANFNR}
                      onChange={(e) => updatePoHeader('ANFNR', e.target.value)}
                      placeholder="입찰번호 (ANFNR)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-lifnr">공급업체 계정 (LIFNR) : 벤더코드 <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-lifnr"
                      value={poData.header.LIFNR}
                      onChange={(e) => updatePoHeader('LIFNR', e.target.value)}
                      placeholder="공급업체 계정 (LIFNR) : 벤더코드"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zproc">처리상태 (ZPROC_IND) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-zproc"
                      value={poData.header.ZPROC_IND}
                      onChange={(e) => updatePoHeader('ZPROC_IND', e.target.value)}
                      placeholder="처리상태 (ZPROC_IND)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-angnr">협상번호 (ANGNR)</Label>
                    <Input
                      id="po-angnr"
                      value={poData.header.ANGNR}
                      onChange={(e) => updatePoHeader('ANGNR', e.target.value)}
                      placeholder="협상번호 (ANGNR)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-waers">통화 (WAERS) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-waers"
                      value={poData.header.WAERS}
                      onChange={(e) => updatePoHeader('WAERS', e.target.value)}
                      placeholder="통화 (WAERS)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zterm">지급조건 (ZTERM) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-zterm"
                      value={poData.header.ZTERM}
                      onChange={(e) => updatePoHeader('ZTERM', e.target.value)}
                      placeholder="지급조건 (ZTERM)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-inco1">인코텀즈1 (INCO1) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-inco1"
                      value={poData.header.INCO1}
                      onChange={(e) => updatePoHeader('INCO1', e.target.value)}
                      placeholder="인코텀즈1 (INCO1)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-inco2">인코텀즈2 (INCO2) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-inco2"
                      value={poData.header.INCO2}
                      onChange={(e) => updatePoHeader('INCO2', e.target.value)}
                      placeholder="인코텀즈2 (INCO2)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-mwskz">세금코드 (MWSKZ) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-mwskz"
                      value={poData.header.MWSKZ}
                      onChange={(e) => updatePoHeader('MWSKZ', e.target.value)}
                      placeholder="세금코드 (MWSKZ)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-lands">국가키 (LANDS) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-lands"
                      value={poData.header.LANDS}
                      onChange={(e) => updatePoHeader('LANDS', e.target.value)}
                      placeholder="국가키 (LANDS)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zrcv-dt">수령일 (ZRCV_DT) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-zrcv-dt"
                      value={poData.header.ZRCV_DT}
                      onChange={(e) => updatePoHeader('ZRCV_DT', e.target.value)}
                      placeholder="수령일 (ZRCV_DT)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zatten-ind">참석지시자 (ZATTEN_IND) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-zatten-ind"
                      value={poData.header.ZATTEN_IND}
                      onChange={(e) => updatePoHeader('ZATTEN_IND', e.target.value)}
                      placeholder="참석지시자 (ZATTEN_IND)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-ihran">입찰마감일 (IHRAN) <span className="text-red-500">*</span></Label>
                    <Input
                      id="po-ihran"
                      value={poData.header.IHRAN}
                      onChange={(e) => updatePoHeader('IHRAN', e.target.value)}
                      placeholder="입찰마감일 (IHRAN)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-text">텍스트 (TEXT)</Label>
                    <Input
                      id="po-text"
                      value={poData.header.TEXT}
                      onChange={(e) => updatePoHeader('TEXT', e.target.value)}
                      placeholder="텍스트 (TEXT)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-lstel">배송지점 (LSTEL)</Label>
                    <Input
                      id="po-lstel"
                      value={poData.header.LSTEL}
                      onChange={(e) => updatePoHeader('LSTEL', e.target.value)}
                      placeholder="배송지점 (LSTEL)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-vstel">출하지점 (VSTEL)</Label>
                    <Input
                      id="po-vstel"
                      value={poData.header.VSTEL}
                      onChange={(e) => updatePoHeader('VSTEL', e.target.value)}
                      placeholder="출하지점 (VSTEL)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zdlv-cntl">납품담당자 (ZDLV_CNTLR)</Label>
                    <Input
                      id="po-zdlv-cntl"
                      value={poData.header.ZDLV_CNTLR}
                      onChange={(e) => updatePoHeader('ZDLV_CNTLR', e.target.value)}
                      placeholder="납품담당자 (ZDLV_CNTLR)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zdlv-price-note">가격노트 (ZDLV_PRICE_NOTE)</Label>
                    <Input
                      id="po-zdlv-price-note"
                      value={poData.header.ZDLV_PRICE_NOTE}
                      onChange={(e) => updatePoHeader('ZDLV_PRICE_NOTE', e.target.value)}
                      placeholder="가격노트 (ZDLV_PRICE_NOTE)"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="po-zdlv-price-t">가격유형 (ZDLV_PRICE_T)</Label>
                    <Input
                      id="po-zdlv-price-t"
                      value={poData.header.ZDLV_PRICE_T}
                      onChange={(e) => updatePoHeader('ZDLV_PRICE_T', e.target.value)}
                      placeholder="가격유형 (ZDLV_PRICE_T)"
                    />
                  </div>
                </div>
              </div>

              <Separator />

              {/* PO 아이템 정보 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="font-semibold">PO 아이템 정보</h4>
                  <Button
                    onClick={addPoItem}
                    size="sm"
                    variant="outline"
                    className="flex items-center gap-1"
                  >
                    <Plus className="h-4 w-4" />
                    아이템 추가
                  </Button>
                </div>

                {poData.items.map((item, index) => (
                  <Card key={index} className="p-4">
                    <div className="flex items-center justify-between mb-4">
                      <h5 className="font-medium">아이템 #{index + 1}</h5>
                      {poData.items.length > 1 && (
                        <Button
                          onClick={() => removePoItem(index)}
                          size="sm"
                          variant="destructive"
                          className="flex items-center gap-1"
                        >
                          <Minus className="h-4 w-4" />
                          삭제
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <div className="space-y-2">
                        <Label>입찰번호 (ANFNR) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.ANFNR}
                          onChange={(e) => updatePoItem(index, 'ANFNR', e.target.value)}
                          placeholder="입찰번호 (ANFNR)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>입찰 아이템번호 (ANFPS) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.ANFPS}
                          onChange={(e) => updatePoItem(index, 'ANFPS', e.target.value)}
                          placeholder="입찰 아이템번호 (ANFPS)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>공급업체 계정 (LIFNR) : 벤더코드 <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.LIFNR}
                          onChange={(e) => updatePoItem(index, 'LIFNR', e.target.value)}
                          placeholder="공급업체 계정 (LIFNR) : 벤더코드"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>순가격 (NETPR) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.NETPR}
                          onChange={(e) => updatePoItem(index, 'NETPR', e.target.value)}
                          placeholder="순가격 (NETPR)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>가격단위 (PEINH) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.PEINH}
                          onChange={(e) => updatePoItem(index, 'PEINH', e.target.value)}
                          placeholder="가격단위 (PEINH)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>주문단위 (BPRME) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.BPRME}
                          onChange={(e) => updatePoItem(index, 'BPRME', e.target.value)}
                          placeholder="주문단위 (BPRME)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>순금액 (NETWR) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.NETWR}
                          onChange={(e) => updatePoItem(index, 'NETWR', e.target.value)}
                          placeholder="순금액 (NETWR)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>총금액 (BRTWR) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.BRTWR}
                          onChange={(e) => updatePoItem(index, 'BRTWR', e.target.value)}
                          placeholder="총금액 (BRTWR)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>납기일 (LFDAT) <span className="text-red-500">*</span></Label>
                        <Input
                          value={item.LFDAT}
                          onChange={(e) => updatePoItem(index, 'LFDAT', e.target.value)}
                          placeholder="납기일 (LFDAT)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>구매오더 품번 (EBELP)</Label>
                        <Input
                          value={item.EBELP}
                          onChange={(e) => updatePoItem(index, 'EBELP', e.target.value)}
                          placeholder="구매오더 품번 (EBELP)"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>계약번호 (ZCON_NO_PO)</Label>
                        <Input
                          value={item.ZCON_NO_PO}
                          onChange={(e) => updatePoItem(index, 'ZCON_NO_PO', e.target.value)}
                          placeholder="계약번호 (ZCON_NO_PO)"
                        />
                      </div>
                    </div>
                  </Card>
                ))}
              </div>

              <Separator />

              <div className="flex gap-4">
                <Button
                  onClick={() => runTest('PO 생성 (샘플)', () => createTestPurchaseOrder())}
                  disabled={isLoading['PO 생성 (샘플)']}
                  variant="outline"
                >
                  {isLoading['PO 생성 (샘플)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Play className="mr-2 h-4 w-4" />
                  샘플 데이터로 테스트
                </Button>
                <Button
                  onClick={() => runTest('PO 생성 (사용자)', async () => {
                    const poRequest = {
                      T_Bidding_HEADER: [poData.header],
                      T_Bidding_ITEM: poData.items,
                      T_PR_RETURN: poData.prReturn
                    }
                    return createPurchaseOrder(poRequest)
                  })}
                  disabled={isLoading['PO 생성 (사용자)']}
                >
                  {isLoading['PO 생성 (사용자)'] && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  <Send className="mr-2 h-4 w-4" />
                  사용자 데이터로 생성 ({poData.items.length}개 아이템)
                </Button>
              </div>

              {/* 테스트 결과 표시 */}
              {(testResults['PO 생성 (샘플)'] || testResults['PO 생성 (사용자)']) && (
                <div className="space-y-2">
                  <h4 className="font-semibold">테스트 결과</h4>
                  {testResults['PO 생성 (샘플)'] && (
                    <TestResultCard result={testResults['PO 생성 (샘플)']} title="샘플 테스트" />
                  )}
                  {testResults['PO 생성 (사용자)'] && (
                    <TestResultCard result={testResults['PO 생성 (사용자)']} title="사용자 테스트" />
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

// 테스트 결과 표시 컴포넌트
function TestResultCard({ result, title }: { result: TestResult; title: string }) {
  return (
    <Alert className={result.success ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}>
      <div className="flex items-center gap-2">
        {result.success ? (
          <CheckCircle className="h-4 w-4 text-green-600" />
        ) : (
          <XCircle className="h-4 w-4 text-red-600" />
        )}
        <span className="font-semibold">{title}</span>
        {typeof result.statusCode !== 'undefined' && (
          <Badge variant="outline" className="text-xs">
            HTTP {result.statusCode}
          </Badge>
        )}
        <Badge variant="outline" className="text-xs">
          {result.duration}ms
        </Badge>
        <span className="text-xs text-muted-foreground ml-auto">
          {result.timestamp}
        </span>
      </div>
      <AlertDescription className="mt-2">
        <div className="space-y-2">
          <p>{result.message}</p>
          {result.endpoint && (
            <p className="text-xs text-muted-foreground break-all"><span className="font-medium">Endpoint:</span> {result.endpoint}</p>
          )}
          {result.headers && (
            <details className="text-xs">
              <summary className="cursor-pointer font-medium">응답 헤더 보기</summary>
              <pre className="mt-2 p-2 bg-gray-100 rounded text-xs overflow-auto max-h-40">
                {Object.entries(result.headers).map(([k, v]) => `${k}: ${v}`).join('\n')}
              </pre>
            </details>
          )}
          {result.requestHeaders && (
            <details className="text-xs">
              <summary className="cursor-pointer font-medium">요청 헤더 보기</summary>
              <pre className="mt-2 p-2 bg-gray-100 rounded text-xs overflow-auto max-h-40">
                {Object.entries(result.requestHeaders).map(([k, v]) => `${k}: ${v}`).join('\n')}
              </pre>
            </details>
          )}
          {result.requestXml && (
            <details className="text-xs">
              <summary className="cursor-pointer font-medium">요청 XML 보기</summary>
              <pre className="mt-2 p-2 bg-gray-100 rounded text-xs overflow-auto max-h-60 whitespace-pre-wrap break-words">
                {result.requestXml}
              </pre>
            </details>
          )}
          {result.responseData && (
            <details className="text-xs">
              <summary className="cursor-pointer font-medium">응답 데이터 보기</summary>
              <pre className="mt-2 p-2 bg-gray-100 rounded text-xs overflow-auto max-h-40">
                {result.responseData}
              </pre>
            </details>
          )}
        </div>
      </AlertDescription>
    </Alert>
  )
}
